﻿using LoadIn.Maps.Bing.Models;
using LoadIn.Maps.Bing.Services;
using LoadIn.Maps.Bing.ViewModels;
using Orchard.Caching;
using Orchard.ContentManagement;
using Orchard.ContentManagement.Drivers;
using Orchard.Environment.Extensions;

namespace LoadIn.Maps.Bing.Drivers
{
    [OrchardFeature("LoadIn.Maps.Bing")]
    public class BingMapsSettingsPartDriver : ContentPartDriver<BingMapsSettingsPart>
    {
        private readonly ISignals _signals;
        private readonly IBingMapsService _bingmapsService;

        protected override string Prefix { get { return "BingMapsSettings"; } }

        public BingMapsSettingsPartDriver(ISignals signals, IBingMapsService bingmapsService)
        {
            _signals = signals;
            _bingmapsService = bingmapsService;
        }

        protected override DriverResult Editor(BingMapsSettingsPart part, dynamic shapeHelper)
        {
            string mapmode = part.Mode;
            if (string.IsNullOrWhiteSpace(mapmode))
                mapmode = "Static";

            return ContentShape("Parts_Loadin_BingMapsSettings",
                               () => shapeHelper.EditorTemplate(
                                   TemplateName: "Parts/LoadIn.BingMapsSettings",
                                   Model: new BingMapsSettingsViewModel
                                   {
                                       ApiKey = part.ApiKey,
                                       Mode = mapmode
                                   },
                                   Prefix: Prefix)).OnGroup("BingMaps");
        }

        protected override DriverResult Editor(BingMapsSettingsPart part, IUpdateModel updater, dynamic shapeHelper)
        {
            updater.TryUpdateModel(part.Record, Prefix, null, null);
            _signals.Trigger("LoadIn.Maps.Bing.Changed");
            return Editor(part, shapeHelper);
        }
    }
}